/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddEditBookDialog.java
 *
 * Created on Mar 30, 2011, 8:16:15 PM
 */

package org.libarae.client;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.SocketTimeoutException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.libarae.client.threads.HasIsbnLookUpThread;
import org.libarae.client.threads.IsbnLookUpThread;
import org.libarae.communication.ClientInterface;
import org.libarae.communication.common.Book;
import org.libarae.communication.request.CreateBookRequest;
import org.libarae.communication.request.EditBookRequest;
import org.libarae.communication.response.Response;

/**
 *
 * @author Casey, Ben
 */
@SuppressWarnings("serial")
public class AddEditBookDialog extends javax.swing.JFrame implements HasIsbnLookUpThread {

    private Book mBook = new Book();
    private int mFlag;
    private MainScreen mMainScreen;

    private final int SCALED_IMAGE_WIDTH = 200;
    private final int SCALED_IMAGE_HEIGHT = 200;

    public static final int ADD_BOOK = 1;
    public static final int EDIT_BOOK = 2;

    /** Creates new form AddEditBookDialog */
    public AddEditBookDialog(int mFlag) {
        this.mFlag = mFlag;

        initComponents();

        switch(mFlag)
        {
            case ADD_BOOK:
                this.setTitle("Add Book");
                btnAddEdit.setText("Add Book");
                cboStatus.setEnabled(false);
                break;
            case EDIT_BOOK:
                this.setTitle("Edit Book");
                btnAddEdit.setText("Edit Book");
                break;
        }
    }

    public AddEditBookDialog(int mFlag, MainScreen mMainScreen) {
        this.mFlag = mFlag;
        this.mMainScreen = mMainScreen;

        initComponents();

        switch(mFlag)
        {
            case ADD_BOOK:
                this.setTitle("Add Book");
                btnAddEdit.setText("Add Book");
                cboStatus.setEnabled(false);
                break;
            case EDIT_BOOK:
                this.setTitle("Edit Book");
                btnAddEdit.setText("Edit Book");
                break;
        }
    }


    public void displayBook(Book b)
    {
        if(b.getTitle() != "")
            fdTitle.setText(b.getTitle());
        if(b.getAuthor() != "")
            fdAuthor.setText(b.getAuthor());
        if(b.getISBN() != "")
            fdISBN.setText(b.getISBN());
        if(b.getPublisher() != "")
            fdPublisher.setText(b.getPublisher());
        if(b.getPubDate() != "")
            fdPubDate.setText(b.getPubDate());
        if(b.getSummary() != "")
            fdSummary.setText(b.getSummary());
        if(b.getBookStatus() != null)
            cboStatus.setSelectedItem(b.getBookStatus().toString());
        if(b.getPicture() != null)
        {
            b.setPicture(scaleImage(b.getPicture()));
            lbPicture.setIcon(new ImageIcon(b.getPicture()));
        }

        mBook = b;

        this.validate();
    }

    private BufferedImage scaleImage(BufferedImage i)
    {
        //Scale the image down;
        int width;
        int height;

        if(i.getWidth() > i.getHeight())
        {
            width = SCALED_IMAGE_WIDTH;
            height = (int)(SCALED_IMAGE_HEIGHT * (((float)i.getHeight())/i.getWidth()));
        }
        else
        {
            height = SCALED_IMAGE_HEIGHT;
            width = (int)(SCALED_IMAGE_WIDTH * (((float)i.getWidth())/i.getHeight()));
        }


        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = newImage.createGraphics();

        g.drawImage(i, 0, 0, width, height, this);
        g.dispose();

        return newImage;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        sepTopSeparator = new javax.swing.JSeparator();
        fdISBNGen = new javax.swing.JTextField();
        btnGenerate = new javax.swing.JButton();
        lbISBNGen = new javax.swing.JLabel();
        lblInformation = new javax.swing.JLabel();
        fdTitle = new javax.swing.JTextField();
        fdAuthor = new javax.swing.JTextField();
        fdISBN = new javax.swing.JTextField();
        fdPubDate = new javax.swing.JTextField();
        lbTitle = new javax.swing.JLabel();
        lbAuthor = new javax.swing.JLabel();
        lbISBN = new javax.swing.JLabel();
        lbPubDate = new javax.swing.JLabel();
        lbSummary = new javax.swing.JLabel();
        btnAddEdit = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnUploadImage = new javax.swing.JButton();
        fdPublisher = new javax.swing.JTextField();
        lbPublisher = new javax.swing.JLabel();
        lbPicture = new javax.swing.JLabel();
        scrSummary = new javax.swing.JScrollPane();
        fdSummary = new javax.swing.JTextPane();
        lblStatus = new javax.swing.JLabel();
        cboStatus = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconImage(new ImageIcon(getClass().getResource("/res/icon.png")).getImage());
        setLocationByPlatform(true);

        btnGenerate.setText("Generate");
        btnGenerate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerateActionPerformed(evt);
            }
        });

        lbISBNGen.setText("ISBN");

        lblInformation.setText("To automatically generate book information, enter an ISBN");

        lbTitle.setText("Title:");

        lbAuthor.setText("Author:");

        lbISBN.setText("ISBN:");

        lbPubDate.setText("Pub. Date:");

        lbSummary.setText("Summary:");

        btnAddEdit.setText("Add/Edit");
        btnAddEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddEditActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnUploadImage.setText("Upload Image");
        btnUploadImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUploadImageActionPerformed(evt);
            }
        });

        lbPublisher.setText("Publisher:");

        lbPicture.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        scrSummary.setViewportView(fdSummary);

        lblStatus.setText("Status:");

        cboStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Available", "Pending", "Checked Out" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(107, 107, 107)
                .addComponent(lbISBNGen)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fdISBNGen, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnGenerate)
                .addContainerGap(156, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sepTopSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 506, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(90, 90, 90)
                .addComponent(lblInformation, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
                .addGap(72, 72, 72))
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(btnUploadImage)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 138, Short.MAX_VALUE)
                .addComponent(btnAddEdit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancel)
                .addGap(101, 101, 101))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbPicture, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbAuthor)
                    .addComponent(lbTitle)
                    .addComponent(lbPubDate)
                    .addComponent(lbSummary)
                    .addComponent(lbISBN)
                    .addComponent(lbPublisher)
                    .addComponent(lblStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrSummary, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                    .addComponent(fdPubDate, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                    .addComponent(fdAuthor, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                    .addComponent(fdTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                    .addComponent(fdISBN, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                    .addComponent(fdPublisher, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                    .addComponent(cboStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInformation)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fdISBNGen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbISBNGen)
                    .addComponent(btnGenerate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sepTopSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fdTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbTitle))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fdAuthor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbAuthor))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fdISBN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbISBN))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fdPublisher, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbPublisher))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fdPubDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbPubDate))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblStatus)
                            .addComponent(cboStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbSummary)
                                .addGap(62, 62, 62))
                            .addComponent(scrSummary, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)))
                    .addComponent(lbPicture, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddEdit)
                    .addComponent(btnCancel)
                    .addComponent(btnUploadImage))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddEditActionPerformed

        if(mFlag == EDIT_BOOK)
        {
            EditBookRequest r = new EditBookRequest();

            mBook.setTitle(fdTitle.getText());
            mBook.setAuthor(fdAuthor.getText());
            mBook.setISBN(fdISBN.getText());
            mBook.setPublisher(fdPublisher.getText());
            mBook.setPubDate(fdPubDate.getText());
            mBook.setSummary(fdSummary.getText());
            switch(cboStatus.getSelectedIndex())
            {
                case 0:
                    mBook.setBookStatus(Book.BookStatus.AVAILABLE);
                    break;
                case 1:
                    mBook.setBookStatus(Book.BookStatus.PENDING);
                    break;
                case 2:
                    mBook.setBookStatus(Book.BookStatus.CHECKED_OUT);
                    break;
            }

            r.setBook(mBook);

            Response response = null;

            try {
                response = ClientInterface.sendRequest(r);
            }
            catch(SocketTimeoutException e)
            {
                JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
                return;
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            if(response == null)
            {
                System.err.println("Error sending to or receiving from server");
            }

            if(response.getStatus() == Response.STATUS_GOOD)
            {
                mMainScreen.getBookInfoPanel().refreshBook();
                this.dispose();
            }
        }
        else
        {
            CreateBookRequest r = new CreateBookRequest();

            mBook.setTitle(fdTitle.getText());
            mBook.setAuthor(fdAuthor.getText());
            mBook.setISBN(fdISBN.getText());
            mBook.setPublisher(fdPublisher.getText());
            mBook.setPubDate(fdPubDate.getText());
            mBook.setSummary(fdSummary.getText());

            r.setBook(mBook);

            Response response = null;

            try {
                response = ClientInterface.sendRequest(r);
            }
            catch(SocketTimeoutException e)
            {
                JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
                return;
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            if(response == null)
            {
                System.err.println("Error sending to or receiving from server");
            }

            if(response.getStatus() == Response.STATUS_GOOD)
            {
                mMainScreen.getUserPagePanel().refreshLists();
                this.dispose();
            }
        }
    }//GEN-LAST:event_btnAddEditActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerateActionPerformed
        IsbnLookUpThread t = new IsbnLookUpThread(fdISBNGen.getText(), this);
        t.start();
    }//GEN-LAST:event_btnGenerateActionPerformed

    private void btnUploadImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadImageActionPerformed
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File pictureFile = fc.getSelectedFile();

            //Get image.
            ImageIcon cover = new ImageIcon(pictureFile.getAbsolutePath());


            //Scale the image down;
            int width;
            int height;
            
            if(cover.getIconWidth() > cover.getIconHeight())
            {
                width = SCALED_IMAGE_WIDTH;
                height = (int)(SCALED_IMAGE_HEIGHT * (((float)cover.getIconHeight())/cover.getIconWidth()));
            }
            else
            {
                height = SCALED_IMAGE_HEIGHT;
                width = (int)(SCALED_IMAGE_WIDTH * (((float)cover.getIconWidth())/cover.getIconHeight()));
            }


            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = bi.createGraphics();

            g.drawImage(cover.getImage(), 0, 0, width, height, this);
            g.dispose();

            mBook.setPicture(bi);

            lbPicture.setIcon(new ImageIcon(mBook.getPicture()));
        }
    }//GEN-LAST:event_btnUploadImageActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AddEditBookDialog(ADD_BOOK).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddEdit;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnGenerate;
    private javax.swing.JButton btnUploadImage;
    private javax.swing.JComboBox cboStatus;
    private javax.swing.JTextField fdAuthor;
    private javax.swing.JTextField fdISBN;
    private javax.swing.JTextField fdISBNGen;
    private javax.swing.JTextField fdPubDate;
    private javax.swing.JTextField fdPublisher;
    private javax.swing.JTextPane fdSummary;
    private javax.swing.JTextField fdTitle;
    private javax.swing.JLabel lbAuthor;
    private javax.swing.JLabel lbISBN;
    private javax.swing.JLabel lbISBNGen;
    private javax.swing.JLabel lbPicture;
    javax.swing.JLabel lbPubDate;
    private javax.swing.JLabel lbPublisher;
    private javax.swing.JLabel lbSummary;
    private javax.swing.JLabel lbTitle;
    private javax.swing.JLabel lblInformation;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JScrollPane scrSummary;
    private javax.swing.JSeparator sepTopSeparator;
    // End of variables declaration//GEN-END:variables

}
